package gek.uni.aspirant.uml.utils.wizzards;

import gek.uni.aspirant.uml.utils.Messages;
import gek.uni.aspirant.uml.utils.UmlUtils;
import gek.uni.aspirant.uml.utils.providers.UmlContentProvider;
import gek.uni.aspirant.uml.utils.providers.UmlLabelProvider;

import java.util.Collection;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.uml2.uml.Model;
import org.eclipse.uml2.uml.UMLPackage;

public class SelectUmlContextElementWizardPage extends WizardPage {

  private Composite treeViewerComposite;
  private Composite browseComposite;
  private TreeViewer modelViewer;
  private Text fileNameTxt;
  private Object element;
  public boolean first = true;

  protected SelectUmlContextElementWizardPage(String pageName) {
    super(pageName);
    setTitle(Messages.SELECT_MODEL_ELEMENT);
  }

  @Override
  public void setVisible(boolean visible) {
    super.setVisible(visible);
//    if (visible == true) {
//      if (first) {
//        try {
//          loadModelFile("/home/arkady/MnemoModel.uml");
//        } catch (Exception e) {
//        }
//        first = false;
//      }
//
//    }
  }

  @Override
  public void createControl(Composite parent) {
    Composite innerComposite = new Composite(parent, SWT.NONE);
    innerComposite.setLayout(new GridLayout(1, true));
    browseComposite = createBrowseComposite(innerComposite);
    browseComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));

    treeViewerComposite = createTreeViewerComposite(innerComposite);
    treeViewerComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
        true));
    setViewerCompositeEnablement(false);

    setControl(innerComposite);
  }

  /**
   * Создает композит, на котором находится тривьювер, в котором отображается
   * иерархия модели
   * 
   * @param parent
   * @return
   */
  protected Composite createTreeViewerComposite(Composite parent) {
    Composite inner = new Composite(parent, SWT.NONE);
    inner.setLayout(new GridLayout(1, true));
    Label lbl = new Label(inner, SWT.NONE);
    lbl.setText(Messages.SELECT_MODEL_ELEMENT);

    modelViewer = new TreeViewer(inner);
    modelViewer.getControl().setLayoutData(
        new GridData(SWT.FILL, SWT.FILL, true, true));
    modelViewer.getControl().setEnabled(false);

    UmlContentProvider contentProvider = new UmlContentProvider();
    UmlLabelProvider labelProvider = new UmlLabelProvider();
    modelViewer.setContentProvider(contentProvider);
    modelViewer.setLabelProvider(labelProvider);
    modelViewer.addSelectionChangedListener(new ISelectionChangedListener() {

      @Override
      public void selectionChanged(SelectionChangedEvent event) {
        ISelection selection = event.getSelection();
        if (selection instanceof IStructuredSelection) {
          element = ((IStructuredSelection) selection).getFirstElement();
        }
      }
    });

    return inner;
  }

  /**
   * Создает композит, на котором нарисован текст и кнопка выбора ресурса модели
   * 
   * @param parent
   * @return
   */
  protected Composite createBrowseComposite(Composite parent) {
    Composite inner = new Composite(parent, SWT.NONE);
    inner.setLayout(new GridLayout(1, true));

    Label browseLbl = new Label(inner, SWT.NONE);
    browseLbl.setText(Messages.SELECT_UML_RESOURCE_LABEL);

    Composite group = new Composite(inner, SWT.NONE);
    group.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));

    group.setLayout(new GridLayout(2, false));
    fileNameTxt = new Text(group, SWT.BORDER | SWT.READ_ONLY);
    fileNameTxt.setBackground(parent.getDisplay().getSystemColor(
        SWT.COLOR_WHITE));
    fileNameTxt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
    fileNameTxt.setText("");
    Button btn = new Button(group, SWT.PUSH);
    btn.setText(Messages.BROWSE_BUTTON_TEXT);
    btn.addSelectionListener(createBrowseResourceButtonListener());
    return inner;
  }

  /**
   * 
   * Делает композайт с деревом активным/неактивным
   */
  private void setViewerCompositeEnablement(boolean enablement) {
    for (Control ctrl : treeViewerComposite.getChildren()) {
      ctrl.setEnabled(enablement);
    }
  }

  /**
   * создает листенер для кнопки выбора модели
   * 
   * @return
   */
  private SelectionListener createBrowseResourceButtonListener() {
    SelectionListener listener = new SelectionListener() {

      @Override
      public void widgetSelected(SelectionEvent e) {
        Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
            .getShell();
        FileDialog dialog = new FileDialog(shell, SWT.OPEN);
        dialog.setFilterExtensions(new String[] { "*.uml" });
        if (dialog.open() != null) {
          String fileName = dialog.getFilterPath() + "/" + dialog.getFileName();
          loadModelFile(fileName);
        }
      }

      @Override
      public void widgetDefaultSelected(SelectionEvent e) {
        // TODO Auto-generated method stub

      }
    };
    return listener;
  }

  private void loadModelFile(String fileName) {
    fileNameTxt.setText(fileName);
    URI uri = URI.createFileURI(fileName);
    Resource resource = UmlUtils.loadResource(uri);
    System.out.println(resource);
    Collection<Model> models = EcoreUtil.getObjectsByType(resource
        .getContents(), UMLPackage.Literals.MODEL);
    modelViewer.setInput(models.toArray());

    setViewerCompositeEnablement(true);
  }

  public Object getUmlElement() {
    return element;
  }
}
